<script setup>
import { ref, onMounted} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getProjects, deleteProject, createProject, updateProject } from '@/api/index.js'
import { Plus, Edit, Delete, Setting } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 添加防抖功能
const debounce = (fn, delay) => {
  let timeoutId
  return (...args) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => fn.apply(null, args), delay)
  }
}
const projects = ref([])
const loading = ref(false)
const createDialogVisible = ref(false)
const editDialogVisible = ref(false)
const createLoading = ref(false)
const editLoading = ref(false)
const currentEditId = ref(null)
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const searchForm = ref({
  name: '',
  status: ''
})



const projectForm = ref({
  name: '',
  intro: '',
  status: 'ACTIVE'
})

const editForm = ref({
  name: '',
  intro: '',
  status: 'ACTIVE'
})

const formRules = {
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 2, max: 100, message: '项目名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  intro: [
    { required: true, message: '请输入项目描述', trigger: 'blur' },
    { min: 5, max: 500, message: '项目描述长度在 5 到 500 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择项目状态', trigger: 'change' }
  ]
}

const projectFormRef = ref()
const editFormRef = ref()

const fetchProjects = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.currentPage,
      size: pagination.value.pageSize,
      name: searchForm.value.name,
      status: searchForm.value.status
    }
    const res = await getProjects(params)
    if (res.status === 200) {
      projects.value = res.data.results || []
      pagination.value.total = res.data.count || 0
    }
  } catch (error) {
    ElMessage.error('获取项目列表失败')
  } finally {
    loading.value = false
  }
}

const debouncedSearch = debounce(() => {
  pagination.value.currentPage = 1
  fetchProjects()
}, 500)

const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchProjects()
}

const handleInputSearch = () => {
  debouncedSearch()
}


const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除此项目吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    const res = await deleteProject(row.id)
    
    // 检查后端返回的 status 字段（现在是 200）
    if (res && res.status === 200) {
      ElMessage.success(res.msg || '删除成功')
      await getProjectList()
    } else {
      ElMessage.error(`删除失败: ${res?.msg || '未知错误'}`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除项目出错:', error)
      // 如果是网络错误或其他错误
      if (error.response) {
        // 服务器响应了错误状态码
        ElMessage.error(`删除失败: ${error.response.data?.msg || error.response.statusText}`)
      } else if (error.request) {
        // 请求已发出但没有收到响应
        ElMessage.error('删除失败: 网络错误')
      } else {
        // 其他错误
        ElMessage.error(`删除失败: ${error.message}`)
      }
    }
  }
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    return new Date(dateString).toLocaleString('zh-CN')
  } catch (error) {
    return '-'
  }
}

const getStatusTag = (status) => {
  const statusMap = {
    'ACTIVE': { type: 'success', text: '进行中' },
    'COMPLETED': { type: 'info', text: '已完成' },
    'ARCHIVED': { type: 'warning', text: '已归档' }
  }
  return statusMap[status] || { type: '', text: status }
}

const statusOptions = [
  { label: '进行中', value: 'ACTIVE' },
  { label: '已完成', value: 'COMPLETED' },
  { label: '已归档', value: 'ARCHIVED' }
]

const showCreateDialog = () => {
  createDialogVisible.value = true
  projectForm.value = {
    name: '',
    intro: '',
    status: 'ACTIVE'
  }
}

const handleCreateSubmit = async () => {
  if (!projectFormRef.value) return
  
  await projectFormRef.value.validate(async (valid) => {
    if (valid) {
      createLoading.value = true
      try {
        const res = await createProject(projectForm.value)
        if (res.status === 201) {
          ElMessage.success('项目创建成功')
          createDialogVisible.value = false
          await fetchProjects()
        }
      } catch (error) {
        ElMessage.error('项目创建失败')
      } finally {
        createLoading.value = false
      }
    }
  })
}

const handleCreateCancel = () => {
  createDialogVisible.value = false
  projectForm.value = {
    name: '',
    intro: '',
    status: 'ACTIVE'
  }
}

const handleEdit = (row) => {
  currentEditId.value = row.id
  editForm.value = {
    name: row.name,
    intro: row.intro,
    status: row.status
  }
  editDialogVisible.value = true
}

const handleEditSubmit = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      editLoading.value = true
      try {
        const res = await updateProject(currentEditId.value, editForm.value)
        if (res.status === 200) {
          ElMessage.success('项目更新成功')
          editDialogVisible.value = false
          await fetchProjects()
        }
      } catch (error) {
        ElMessage.error('项目更新失败')
      } finally {
        editLoading.value = false
      }
    }
  })
}

const handleEditCancel = () => {
  editDialogVisible.value = false
  editForm.value = {
    name: '',
    intro: '',
    status: 'ACTIVE'
  }
  currentEditId.value = null
}

onMounted(() => {
  fetchProjects()
})
</script>

<template>
  <div class="project-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>项目管理</span>
          <el-button type="primary" :icon="Plus" @click="showCreateDialog">
            新建项目
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="项目名称">
            <el-input v-model="searchForm.name" placeholder="请输入项目名称" clearable @input="handleInputSearch" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              @change="handleSearch"
            >
              <el-option
                v-for="option in statusOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table :data="projects" v-loading="loading" stripe>
        <el-table-column prop="name" label="项目名称" />
        <el-table-column prop="intro" label="项目描述" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status).type">
              {{ getStatusTag(scope.row.status).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_time || scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.updated_time || scope.row.updated_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" :icon="Setting" @click="router.push(`/project/${scope.row.id}/environments`)">
              环境配置
            </el-button>
            <el-button size="small" type="primary" :icon="Edit" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchProjects"
          @current-change="fetchProjects"
        />
      </div>
    </el-card>

    <!-- 创建项目对话框 -->
    <el-dialog 
      v-model="createDialogVisible" 
      title="创建项目" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="projectFormRef"
        :model="projectForm"
        :rules="formRules"
        label-width="80px"
        size="default"
      >
        <el-form-item label="项目名称" prop="name">
          <el-input
            v-model="projectForm.name"
            placeholder="请输入项目名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="项目描述" prop="intro">
          <el-input
            v-model="projectForm.intro"
            type="textarea"
            placeholder="请输入项目描述"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="项目状态" prop="status">
          <el-radio-group v-model="projectForm.status">
            <el-radio label="ACTIVE">进行中</el-radio>
            <el-radio label="COMPLETED">已完成</el-radio>
            <el-radio label="ARCHIVED">已归档</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCreateCancel">取消</el-button>
          <el-button type="primary" @click="handleCreateSubmit" :loading="createLoading">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑项目对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑项目" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="formRules"
        label-width="80px"
        size="default"
      >
        <el-form-item label="项目名称" prop="name">
          <el-input
            v-model="editForm.name"
            placeholder="请输入项目名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="项目描述" prop="intro">
          <el-input
            v-model="editForm.intro"
            type="textarea"
            placeholder="请输入项目描述"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="项目状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio label="ACTIVE">进行中</el-radio>
            <el-radio label="COMPLETED">已完成</el-radio>
            <el-radio label="ARCHIVED">已归档</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleEditCancel">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit" :loading="editLoading">
            更新
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.project-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-area {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }

  .pagination-area {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>